# -*- coding: utf-8 -*-

import cv2
import numpy as np
from PIL import ImageFont, ImageDraw, Image
import threading
import time
import subprocess

# 加载分类器
recognizer = cv2.face.LBPHFaceRecognizer_create()
# 读取训练数据
recognizer.read('./data/face_trainer.yml')
# 名称
names = ['未知', '胡歌','刘亦菲','范冰冰', '刘德华','刘毛','刘祖民' ]
# 警报全局变量
warningtime = 0
# 设置字体相关参数
font_path = './data/font/simfang.ttf'


def cv2ImgAddText(img, text, left, top, textColor=(0, 0, 255), textSize=20):
    """
    文字转换为图片并添加到图片上
    """
    if (isinstance(img, np.ndarray)):  # 判断是否OpenCV图片类型
        img = Image.fromarray(cv2.cvtColor(img, cv2.COLOR_BGR2RGB))
    # 创建一个可以在给定图像上绘图的对象
    draw = ImageDraw.Draw(img)
    # 字体的格式
    fontStyle = ImageFont.truetype(
        font_path, textSize, encoding="utf-8")
    # 绘制文本
    draw.text((left, top), text, textColor, font=fontStyle)

    # 转换回OpenCV格式
    return cv2.cvtColor(np.asarray(img), cv2.COLOR_RGB2BGR)


# 人脸检测
def detect_face(src_img):
    # 导入人脸检测模型
    face_cascade = cv2.CascadeClassifier('D:/InstallationPath/OpenCV/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml')
    # 灰度转换
    gray = cv2.cvtColor(src_img, cv2.COLOR_BGR2GRAY)
    faces = face_cascade.detectMultiScale(gray)  # 灰度图像，缩放因子，最小邻域，最大邻域，最小尺寸，最大尺寸
    # 绘制人脸矩形
    for (x, y, w, h) in faces:
        cv2.rectangle(src_img, (x, y), (x + w, y + h), (0, 0, 255), 2)  # 图片，左上角坐标，右下角坐标，颜色，线宽
        # 人脸识别
        id, confidence = recognizer.predict(gray[y:y + h, x:x + w])
        print(id)
        # 判断是否为本人
        if confidence < 70:
            name = names[id]
            confidence = "{0}%".format(round(100 - confidence))
        else:
            name = "unknown"
            confidence = "{0}%".format(round(100 - confidence))
        # 绘制姓名
        src_img = cv2ImgAddText(src_img, name, x + 5, y + 5, (255, 0, 0), 50)
        # 绘制置信度
        src_img = cv2ImgAddText(src_img, confidence, x + 5, y + h - 30, (255, 0, 0), 50)
        # cv2.putText(img, name, (x, y), cv2.FONT_HERSHEY_COMPLEX, 1, (128, 128, 0), 2)
        print('标签id:', id, '置信评分:', confidence)
        # 判断是否为本人

        if name == "unknown":
            # 警报
            global warningtime
            warningtime += 1
            # 警报超过3次
            if warningtime > 3:
                # 发送邮件
                # sendEmail()
                print("警报")
                # 重置警报次数
                warningtime = 0
    return src_img



# 关闭
if __name__ == '__main__':
    # 读取摄像头
    cap = cv2.VideoCapture(0)  # 0代表默认摄像头编号，如果有多个摄像头，可以尝试1，2，3等等
    # cap = cv.VideoCapture("./images/video.mp4")#读取视频文件
    # cap = cv2.VideoCapture('rtmp://')  # 读取视频流
    cap.set(cv2.CAP_PROP_FPS, 30)  # 设置帧率
    cap.set(cv2.CAP_PROP_BUFFERSIZE, 1)  # 设置缓冲区大小为1，你可以根据需要调整


    # 人脸检测
    while True:
        ret, frame = cap.read()
        if ret:
            img = detect_face(frame)
            # 显示图片
            cv2.imshow("img", img)
            time.sleep(0.1)
            # 等待键盘输入
            if cv2.waitKey(1) == ord('q'):
                break
    # 释放资源
    cap.release()
    cv2.destroyAllWindows()

    # # 读取图片
    # img = cv2.imread("./images/img_5.png")
    # img = detect_face(img)    # # 修改图片大小
    # img = cv2.resize(img, (800, 600))
    # cv2.imshow("face_detect", img)
    # cv2.waitKey(0)
    # cv2.destroyAllWindows()